﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace ImagesToDatabase
{
    public class DatabaseImagesProcessor
    {
        public static void Main(string[] args)
        {
            string dirName = "../../Images";
            LoadImages(dirName);
        }

        public static void LoadImages(string dirName)
        {
            BookstoreDataContext context = new BookstoreDataContext();
            string[] files = Directory.GetFiles(dirName);
            using (context)
            {
                foreach (string file in files)
                {
                    string[] buf = file.Split(new char[] { '.', '/', '\\' });
                    string bookName = buf[buf.Length - 2];
                    Book book = LoadBook(bookName);
                    if (book == null)
                    {
                        Console.WriteLine("Image {0} will not be uploaded because there is no book with ISBN {1}.", file, bookName);
                        continue;
                    }
                    DeletePreviousImage(book);
                    Image image = new Image();
                    Console.WriteLine(file);
                    image.BookID = book.BookID;
                    image.Picture = File.ReadAllBytes(file);
                    context.Images.InsertOnSubmit(image);
                    context.SubmitChanges(); 
                }
            }
        }

        public static Book LoadBook(string isbn)
        {
            BookstoreDataContext context = new BookstoreDataContext();
            using (context)
            {
               Book book =
                (from b in context.Books
                 where b.ISBN == isbn
                 select b).SingleOrDefault();
               return book;
            }
         }

        public static void DeletePreviousImage(Book book)
        {
            BookstoreDataContext context = new BookstoreDataContext();
            List<Image> imagesToDelete = new List<Image>();

            using (context)
            {
               Image oldImage =
                      (from bi in context.Images
                       where bi.BookID == book.BookID
                       select bi).SingleOrDefault();
               if (oldImage != null)
               {
                   context.Images.DeleteOnSubmit(oldImage);
                   context.SubmitChanges();
               }                
            }
        }
    }
}
